package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.dto.output.ErrorOutputDto;
import com.b511.swpu.cementbackend.dto.output.PageOutputDto;
import com.b511.swpu.cementbackend.entity.CementBaseEntity;
import com.b511.swpu.cementbackend.service.BoreholeService;
import com.b511.swpu.cementbackend.dto.input.BoreholeConditionInputDto;
import com.b511.swpu.cementbackend.entity.Borehole;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.BoreholeRepository;
import com.b511.swpu.cementbackend.util.*;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class BoreholeServiceImpl implements BoreholeService {

    private final BoreholeRepository boreholeRepository;

    private final UnitUtil unitUtil;

    private final ValidateUtil validateUtil;

    public BoreholeServiceImpl(BoreholeRepository boreholeRepository, UnitUtil unitUtil, ValidateUtil validateUtil) {
        this.boreholeRepository = boreholeRepository;
        this.unitUtil = unitUtil;
        this.validateUtil = validateUtil;
    }

    @Override
    public R getBoreholeByCondition(BoreholeConditionInputDto boreholeConditionInputDto, PageRequest pageRequest) {
        Page<Borehole> page = boreholeRepository.findAll((Specification<Borehole>) (root, cq, cb)
                -> Help.createPredicate(boreholeConditionInputDto, root, cb), pageRequest);
        List<Borehole> content = page.getContent();
        // unitUtil.transformUnit(content, Borehole.class, null);
        return R.ok().putData(new PageOutputDto<>(page.getTotalElements(), content));
    }

    @Override
    @Transactional
    public R updateBorehole(Long id, Borehole updateBorehole) {
        Optional<Borehole> optionalBorehole = boreholeRepository.findById(id);
        if (!optionalBorehole.isPresent()) {
            throw new CementException(Code.SELECT_FAIL);
        }
        Borehole borehole = optionalBorehole.get();
        CopyUtil.copyProperties(updateBorehole, borehole);
//        ErrorOutputDto validate = validateUtil.validate(updateBorehole);
        boreholeRepository.save(borehole);
        return R.ok();
    }

    @Override
    public R getAllBorehole() {
        return R.ok().putData(boreholeRepository.findAll());
    }

    @Override
    public R validateBorehole() {
        List<Borehole> all = boreholeRepository.findAll();
//        validateUtil.validate((CementBaseEntity) all)
        return R.ok().putData(all);
    }
}
